package com.skyline.wo.controller;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.skyline.base.controller.BaseController;
import com.skyline.base.exception.NoResourceException;
import com.skyline.base.exception.NoVisitPermissionException;
import com.skyline.base.type.Activity;
import com.skyline.base.type.Authority;
import com.skyline.common.bean.Page;
import com.skyline.common.util.AuthorityUtil;
import com.skyline.common.util.Constant;
import com.skyline.common.util.ViewPaths;
import com.skyline.common.util.WebHelper;
import com.skyline.user.model.User;
import com.skyline.wo.model.Article;
import com.skyline.wo.model.Category;
import com.skyline.wo.service.ArticleService;
import com.skyline.wo.service.CategoryService;

/**
 * 日志模块的Controller
 * 
 * @author Jairus Chan
 * 
 */
@Controller
@RequestMapping("/article")
public class ArticleController extends BaseController {

//	private static final Log LOGGER = LogFactory.getLog(ArticleController.class);

	@Autowired
	private CategoryService categoryService;

	@Autowired
	private ArticleService articleService;

	// @Autowired
	// private AuthorityUtil authorityUtil;

//	private @Value("${view.aricle.listarticle}")
//	String listArticleView;
//
//	private @Value("${view.aricle.addarticle}")
//	String addArticleView;
//
//	private @Value("${view.aricle.viewarticle}")
//	String viewArticleView;
//
//	private @Value("${view.user.login}")
//	String userLoginView;
//
//	private @Value("${view.article.managecategory}")
//	String manageCategoryView;
//
//	private @Value("${view.article.modifyarticle}")
//	String modifyArticleView;

	private @Value("${article.listarticle.pagesize}")
	Integer listArticlePageSize;

	private String requestFrom = "article/category/manage" + URL_SUFFIX;

	@RequestMapping(value = "/list/user/{userid}", method = RequestMethod.GET)
	public ModelAndView listArticleByUserId(Page page, @PathVariable Long userid) {
		ModelAndView mav = new ModelAndView();
		// Page page = new Page();
		page.setSize(listArticlePageSize);
		// page.setCurpage(1);
		Integer authority = AuthorityUtil.getAuthority(null, userid);
		List<Article> articles = articleService.getArticleByOwnerId(page, userid, authority);
		mav.addObject("ARTICLES", articles);
		mav.setViewName(ViewPaths.ARTICLE_LISTARTICLE);
		mav.addObject("OWNER_ID", userid);
		List<Category> categories = categoryService.getCategoryByOwnerId(userid);
		Category category = new Category();
		category.setId(Long.valueOf(0));
		category.setCategoryName("全部日志");
		categories.add(0, category);
		mav.addObject("CATEGORIES", categories);
		mav.addObject("AUTHORITY", authority);
		mav.addObject("CURRENT_CATEGORY", Long.valueOf(0));
		mav.addObject("page", page);
		return mav;
	}

	@RequestMapping(value = "/list/category/{ownerId}/{categoryId}", method = RequestMethod.GET)
	public ModelAndView listArticleByCategoryId(Page page, @PathVariable Long categoryId, @PathVariable Long ownerId) {
		ModelAndView mav = new ModelAndView();
		Category currentCategory = categoryService.getCategoryById(categoryId);
		if (currentCategory != null) {
			// Page page = new Page();
			page.setSize(listArticlePageSize);
			// page.setCurpage(1);
			Integer authority = AuthorityUtil.getAuthority(null, currentCategory.getId());

			List<Article> articles = articleService.getArticleByCategoryId(page, categoryId, ownerId, authority);
			mav.addObject("ARTICLES", articles);

			mav.setViewName(ViewPaths.ARTICLE_LISTARTICLE);
			mav.addObject("CATEGORY_Id", categoryId);

			List<Category> categories = categoryService.getCategoryByOwnerId(currentCategory.getOwnerId());
			Category category = new Category();
			category.setId(Long.valueOf(0));
			category.setCategoryName("全部日志");
			categories.add(0, category);
			mav.addObject("CATEGORIES", categories);

			mav.addObject("CURRENT_CATEGORY", categoryId);

			mav.addObject("OWNER_ID", currentCategory.getOwnerId());
			mav.addObject("page", page);

			mav.addObject("AUTHORITY", authority);
			return mav;
		} else {
			throw new NoResourceException("ID为"+categoryId+"的分类不存在");
			// return null;
		}
	}

	@RequestMapping(value = "/view/{articleId}", method = RequestMethod.GET)
	public ModelAndView viewArticleByArticleId(@PathVariable Long articleId) {
		// Date d1=new Date();
		ModelAndView mav = new ModelAndView();
		Article article = articleService.getArticleById(articleId);
		Integer authority = checkAndReturnAuthority(article);
		
		articleService.addVisitNum(articleId);
		
		mav.addObject("ARTICLE", article);
		mav.addObject("AUTHORITY", authority);
		mav.setViewName(ViewPaths.ARTICLE_VIEWARTICLE);
		// Date d2=new Date();
		// System.out.println(d2.getTime()-d1.getTime());
		return mav;
	}

	@RequestMapping(value = "/prior/{categoryId}/{articleId}/{readAuthority}", method = RequestMethod.GET)
	public ModelAndView viewPriorArticle(@PathVariable Long articleId, @PathVariable Long categoryId, @PathVariable Integer readAuthority) {
		// Date d1=new Date();
		ModelAndView mav = new ModelAndView();
		Article article = articleService.getPriorArticle(categoryId, articleId, readAuthority);
		if (article != null) {
			Integer authority = AuthorityUtil.getAuthority(null, article.getOwnerId());
			if (authority < readAuthority || authority < article.getAuthority()) {
				throw new NoVisitPermissionException();
			} else {
				mav.addObject("AUTHORITY", authority);
				articleService.addVisitNum(articleId);
			}
		} else {
			return viewArticleByArticleId(articleId);
		}
		mav.addObject("ARTICLE", article);
		mav.setViewName(ViewPaths.ARTICLE_VIEWARTICLE);
		// Date d2=new Date();
		// System.out.println(d2.getTime()-d1.getTime());
		return mav;
	}

	@RequestMapping(value = "/next/{categoryId}/{articleId}/{readAuthority}", method = RequestMethod.GET)
	public ModelAndView viewNextArticle(@PathVariable Long articleId, @PathVariable Long categoryId, @PathVariable Integer readAuthority) {
		ModelAndView mav = new ModelAndView();
		Article article = articleService.getNextArticle(categoryId, articleId, readAuthority);
		if (article != null) {
			Integer authority = AuthorityUtil.getAuthority(null, article.getOwnerId());
			if (authority < readAuthority || authority < article.getAuthority()) {
				throw new NoVisitPermissionException();
			} else {
				mav.addObject("AUTHORITY", authority);
				articleService.addVisitNum(articleId);
			}
		} else {
			return viewArticleByArticleId(articleId);
		}
		mav.addObject("ARTICLE", article);
		mav.setViewName(ViewPaths.ARTICLE_VIEWARTICLE);
		return mav;
	}

	@RequestMapping(value = "add", method = RequestMethod.GET)
	public ModelAndView addArticleRequest() {
		User user = (User) WebHelper.getSessionAttribute(null, Constant.SESSION_USER);
		ModelAndView mav = new ModelAndView();
		if (user != null) {
			mav.setViewName(ViewPaths.ARTICLE_ADDARTICLE);
			List<Category> categories = categoryService.getCategoryByOwnerId(user.getId());
			mav.addObject("CATEGORIES", categories);
		} else {
			mav.addObject("REQUEST_FROM", "article/add" + URL_SUFFIX);
			mav.setViewName(ViewPaths.USER_LOGIN);
		}
		return mav;
	}

	@RequestMapping(value = "add", method = RequestMethod.POST)
	public ModelAndView addArticleExecute(String title, String content, String digest, Long categoryId, String categoryName,
			Integer authority, String submitToken) {
		User user = (User) WebHelper.getSessionAttribute(null, Constant.SESSION_USER);
		ModelAndView mav = new ModelAndView();
		if (user != null) {
			Article article = new Article(authority, user.getId(), user.getPortrait(), user.getNickname(), title, content, digest,
					categoryId, categoryName);
			article.setSubmitToken(submitToken);
			// //
			String errMsg = validateForm("addArticleForm", article);
			if (errMsg != null) {
				ModelAndView returnMav = addArticleRequest();
				return processValidationErrors("errMsg", errMsg, returnMav);
			}
			// //
			articleService.addArticle(article);
			//FIXME 不要用redirect
			mav.setViewName("redirect:" + "list/user/" + user.getId() + URL_SUFFIX);
		} else {
			mav.addObject("REQUEST_FROM", "article/add" + URL_SUFFIX);
			mav.setViewName(ViewPaths.USER_LOGIN);
		}
		return mav;
	}

	@RequestMapping(value = "delete/{articleId}", method = RequestMethod.GET)
	public ModelAndView deleteArticle(@PathVariable Long articleId) {
		User user = (User) WebHelper.getSessionAttribute(null, Constant.SESSION_USER);
		ModelAndView mav = new ModelAndView();
		if (user != null) {
			articleService.deleteArticle(articleId, user.getId());
			//FIXME 不要用redirect
			mav.setViewName("redirect:" + "../list/user/" + user.getId() + URL_SUFFIX);
		} else {
			mav.addObject("REQUEST_FROM", "article/add" + URL_SUFFIX);
			mav.setViewName(ViewPaths.USER_LOGIN);
		}
		return mav;
	}

	@RequestMapping(value = "modify/{articleId}", method = RequestMethod.GET)
	public ModelAndView modifyArticleRequest(@PathVariable Long articleId) {
		User user = (User) WebHelper.getSessionAttribute(null, Constant.SESSION_USER);
		ModelAndView mav = new ModelAndView();
		if (user != null) {
			Article article = articleService.getArticleById(articleId);
			if (article != null && article.getOwnerId().equals(user.getId())) {
				List<Category> categories = categoryService.getCategoryByOwnerId(user.getId());
				mav.addObject("ARTICLE", article);
				mav.addObject("CATEGORIES", categories);
				mav.setViewName(ViewPaths.ARTICLE_MODIFYARTICLE);
			} else {
				mav.addObject("REQUEST_FROM", "article/modify/" + articleId + URL_SUFFIX);
				mav.setViewName(ViewPaths.USER_LOGIN);
			}
		} else {
			mav.addObject("REQUEST_FROM", "article/modify/" + articleId + URL_SUFFIX);
			mav.setViewName(ViewPaths.USER_LOGIN);
		}
		return mav;
	}

	@RequestMapping(value = "modify/{articleId}", method = RequestMethod.POST)
	public ModelAndView modifyArticleExecute(@PathVariable Long articleId, String title, String content, String digest, Long categoryId,
			String categoryName, Integer authority, String submitToken) {
		User user = (User) WebHelper.getSessionAttribute(null, Constant.SESSION_USER);
		ModelAndView mav = new ModelAndView();
		if (user != null) {
			Article article = new Article(authority, user.getId(), user.getPortrait(), user.getNickname(), title, content, digest,
					categoryId, categoryName);
			article.setSubmitToken(submitToken);
			// //
			String errMsg = validateForm("modifyArticleForm", article);
			if (errMsg != null) {
				ModelAndView returnMav = modifyArticleRequest(articleId);
				return processValidationErrors("errMsg", errMsg, returnMav);
			}
			// //
			articleService.modifyArticle(articleId, authority, user.getId(), title, content, digest, categoryId, categoryName);
			//FIXME 不要用redirect
			mav.setViewName("redirect:../view/" + articleId + URL_SUFFIX);
		} else {
			mav.addObject("REQUEST_FROM", "article/modify/" + articleId + URL_SUFFIX);
			mav.setViewName(ViewPaths.USER_LOGIN);
		}
		return mav;
	}

	@RequestMapping(value = "up/{articleId}", method = RequestMethod.POST)
	public @ResponseBody
	void up(@PathVariable Long articleId) {
		articleService.up(articleId);
	}

	@RequestMapping(value = "down/{articleId}", method = RequestMethod.POST)
	public @ResponseBody
	void down(@PathVariable Long articleId) {
		articleService.down(articleId);
	}

	@RequestMapping(value = "category/manage", method = RequestMethod.GET)
	public ModelAndView manageCategory() {
		User user = (User) WebHelper.getSessionAttribute(null, Constant.SESSION_USER);
		ModelAndView mav = new ModelAndView();
		if (user != null) {
			List<Category> categories = categoryService.getCategoryByOwnerId(user.getId());
			mav.setViewName(ViewPaths.ARTICLE_MANAGECATEGORY);
			// mav.addObject(userid);
			mav.addObject("CATEGORIES", categories);
		} else {
			mav.addObject("REQUEST_FROM", requestFrom);
			mav.setViewName(ViewPaths.USER_LOGIN);
		}
		return mav;
	}

	@RequestMapping(value = "category/add", method = RequestMethod.POST)
	public ModelAndView addCategory(String categoryName) {

		User user = (User) WebHelper.getSessionAttribute(null, Constant.SESSION_USER);
		ModelAndView mav = new ModelAndView();
		if (user != null) {
			//FIXME 不要使用redirect
			categoryService.createCategory(user.getId(), user.getPortrait(), user.getNickname(), categoryName, Activity.NORMAL);
			mav.setViewName("redirect:" + "manage" + URL_SUFFIX);
		} else {
			mav.addObject("REQUEST_FROM", requestFrom);
			mav.setViewName(ViewPaths.USER_LOGIN);
		}
		return mav;
	}

	@RequestMapping(value = "category/ajaxadd")
	public @ResponseBody
	List<Category> ajaxAddCategory(String categoryName) {
		User user = (User) WebHelper.getSessionAttribute(null, Constant.SESSION_USER);
		if (user != null
				&& categoryService.createCategory(user.getId(), user.getPortrait(), user.getNickname(), categoryName, Activity.NORMAL)) {
			return categoryService.getCategoryByOwnerId(user.getId());
		} else {
			return null;
		}
	}

	@RequestMapping(value = "category/modify", method = RequestMethod.POST)
	public ModelAndView modifyCategory(Long id, String categoryName) {

		User user = (User) WebHelper.getSessionAttribute(null, Constant.SESSION_USER);
		ModelAndView mav = new ModelAndView();
		Category category = categoryService.getCategoryById(id);
		if (user != null && category != null && user.getId().equals(category.getOwnerId())) {
			//FIXME 不要使用redirect
			categoryService.modifyCategory(id, categoryName, user.getId());
			mav.setViewName("redirect:" + "manage" + URL_SUFFIX);
		} else {
			mav.addObject("REQUEST_FROM", requestFrom);
			mav.setViewName(ViewPaths.USER_LOGIN);
		}
		return mav;
	}

	@RequestMapping(value = "category/delete/{id}", method = RequestMethod.GET)
	public ModelAndView deleteCategory(@PathVariable Long id) {
		User user = (User) WebHelper.getSessionAttribute(null, Constant.SESSION_USER);
		// TODO:获取对该分类的访问权限；
		Integer authority = Authority.PRIVATE;
		ModelAndView mav = new ModelAndView();
		Category category = categoryService.getCategoryById(id);
		if (user != null && category != null && user.getId().equals(category.getOwnerId())) {
			// categoryService.modifyCategory(id, authority,
			//FIXME 不要使用redirect
			categoryService.deleteCategory(id, user.getId(), authority);
			mav.setViewName("redirect:" + "../manage" + URL_SUFFIX);
		} else {
			mav.addObject("REQUEST_FROM", requestFrom);
			mav.setViewName(ViewPaths.USER_LOGIN);
		}
		return mav;
	}
}
